package com.farm.wcp.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.farm.core.auth.domain.LoginUser;
import com.farm.core.page.ViewMode;
import com.farm.doc.domain.FarmDocShare;
import com.farm.doc.domain.FarmDocfile;
import com.farm.doc.domain.FarmDoctext;
import com.farm.doc.domain.FarmDoctype;
import com.farm.doc.domain.ex.DocBrief;
import com.farm.doc.domain.ex.DocEntire;
import com.farm.doc.exception.CanNoReadException;
import com.farm.doc.exception.DocNoExistException;
import com.farm.doc.server.FarmDocManagerInter;
import com.farm.doc.server.FarmDocRunInfoInter;
import com.farm.doc.server.FarmDocShareInter;
import com.farm.parameter.FarmParameterService;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;

/**
 * 分享文章
 * 
 * @author yangyining@deliveirk.com
 *
 */
@RequestMapping("/docshare")
@Controller
public class DocShareController extends WebUtils {
	private final static Logger log = Logger.getLogger(DocController.class);
	@Resource
	private FarmDocShareInter farmDocShareInter;

	@Resource
	private FarmDocManagerInter farmDocManagerImpl;

	@Resource
	private FarmDocRunInfoInter farmDocRunInfoImpl;

	/**
	 * 共享文档
	 * 
	 * @return
	 */
	@RequestMapping("/initDocShare")
	public ModelAndView initDocShare(String id, HttpSession session) {
		// 获取当前登录用户
		LoginUser loginUser = getCurrentUser(session);
		if (loginUser == null) {

		}
		ViewMode viewMode = ViewMode.getInstance();
		try {
			// 内网IP
			String intranetip = FarmParameterService.getInstance().getParameter("config.sys.intranetip");
			// 外网IP
			String internetip = FarmParameterService.getInstance().getParameter("config.sys.internetip");

			FarmDocShare insertEntity = farmDocShareInter.createDocShare(id, loginUser);
			viewMode.putAttr("intranetlink", intranetip + "/docshare/look/Pub" + insertEntity.getId() + ".html");
			viewMode.putAttr("internetlink", internetip + "/docshare/look/Pub" + insertEntity.getId() + ".html");
			viewMode.putAttr("linkPwd", insertEntity.getPwd());

			return viewMode.returnModelAndView(ThemesUtil.getThemePath() + "/know/docShare");
		} catch (Exception e) {
			log.error(e.getMessage());
			return viewMode.setError(e.toString()).returnModelAndView(ThemesUtil.getThemePath() + "/error");
		}
	}

	/**
	 * 查看共享文档
	 * 
	 * @return
	 */
	@RequestMapping(value = "/look/Pub{shareid}", method = RequestMethod.GET)
	public ModelAndView lookDocShare(@PathVariable("shareid") String id, HttpSession session,
			HttpServletRequest request) {

		FarmDocShare farmDocShare = farmDocShareInter.queryDocShareById(id);
		String docid = farmDocShare.getDocid();

		ViewMode page = ViewMode.getInstance();
		page.putAttr("shareid", id);

		

		try {
			DocEntire doc = farmDocManagerImpl.getDoc(docid, getCurrentUser(session));
			page.putAttr("DOCE", doc);
			String pwd = request.getParameter("pwd");
			if (StringUtils.isBlank(pwd)) {
				return page.returnModelAndView(ThemesUtil.getThemePath() + "/know/docSharePwdVld");
			}
			
			if (!pwd.equals(farmDocShare.getPwd())) {
				page.putAttr("errormsg", "提取码不正确，请重新输入！");
				page.putAttr("pwd", pwd);
				return page.returnModelAndView(ThemesUtil.getThemePath() + "/know/docSharePwdVld");
			}
			
			List<FarmDoctext> versions = farmDocManagerImpl.getDocVersions(docid);
			page.putAttr("VERSIONS", versions);
			if (getCurrentUser(session) != null) {
				boolean isenjoy = farmDocRunInfoImpl.isEnjoyDoc(getCurrentUser(session).getId(), docid);
				page.putAttr("ISENJOY", isenjoy);
			}
			FarmDoctype type = doc.getType();
			page.putAttr("TYPEID", type == null ? "" : type.getId());
			Set<String> fileTypes = new HashSet<String>();
			for (FarmDocfile node : doc.getFiles()) {
				fileTypes.add(node.getExname().trim().replace(".", "").toUpperCase());
			}
			page.putAttr("FILETYPES", fileTypes);
			farmDocRunInfoImpl.visitDoc(docid, getCurrentUser(session), getCurrentIp(request));
			LoginUser user = getCurrentUser(session);
			if (type != null) {
				List<DocBrief> typedocs = farmDocRunInfoImpl.getTypeDocs(type == null ? "" : type.getId(),
						user == null ? "none" : user.getId(), 10);
				page.putAttr("TYPEDOCS", typedocs);
			}
			if (doc.getDoc().getDomtype().equals("1")) {
				return page.returnModelAndView(ThemesUtil.getThemePath() + "/know/view");
			}
			if (doc.getDoc().getDomtype().equals("5")) {
				return page.returnModelAndView(ThemesUtil.getThemePath() + "/webfile/webfile");
			}
			if (doc.getDoc().getDomtype().equals("4")) {
				return page.putAttr("groupid", doc.getGroup().getId()).returnRedirectUrl("/webgroup/Pubshow.do");
			}
		} catch (CanNoReadException e) {
			return ViewMode.getInstance().setError(e.toString())
					.returnModelAndView(ThemesUtil.getThemePath() + "/error");
		} catch (DocNoExistException e) {
			return ViewMode.getInstance().setError(e.toString())
					.returnModelAndView(ThemesUtil.getThemePath() + "/error");
		} catch (Exception e) {
			e.printStackTrace();
			return ViewMode.getInstance().setError(e.toString())
					.returnModelAndView(ThemesUtil.getThemePath() + "/error");
		}
		return ViewMode.getInstance().setError("请实现正确的DOCTYPE类型解析")
				.returnModelAndView(ThemesUtil.getThemePath() + "/error");
	}
}
